#define _CRT_SECURE_NO_WARNINGS 1

//#include<iostream>
//
//using namespace std;
//
//const int N = 110;
//
//int w[N];
//int f[N][N];
//int n;
//
//int main()
//{
//    scanf("%d", &n);
//    for (int i = 1; i <= n; i++)   scanf("%d", &w[i]);
//
//    for (int len = 1; len <= n; len++)
//        for (int i = 1; i + len - 1 <= n; i++)
//        {
//            int j = i + len - 1;
//            f[i][j] = max(w[i] - f[i + 1][j], w[j] - f[i][j - 1]);
//        }
//
//    int sum = 0, d = f[1][n];
//    for (int i = 1; i <= n; i++)   sum += w[i];
//    printf("%d %d", (sum + d) / 2, (sum - d) / 2);
//    return 0;
//}

#include<iostream>
#include<cstring>

using namespace std;

const int N = 40010, M = N * 2;

int n, m;
int h[N], e[M], ne[M], idx;
int depth[N], f[N][16];
int q[N];

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void bfs(int root)
{
    memset(depth, 0x3f, sizeof depth);
    depth[0] = 0, depth[root] = 1;
    int hh = 0, tt = 0;
    q[0] = root;

    while (hh <= tt)
    {
        int t = q[hh++];
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (depth[j] > depth[t] + 1)
            {
                depth[j] = depth[t] + 1;
                q[++tt] = j;
                f[j][0] = t;
                for (int k = 1; k <= 15; k++)
                    f[j][k] = f[f[j][k - 1]][k - 1];
            }
        }
    }
}

int lca(int a, int b)
{
    if (depth[a] < depth[b]) swap(a, b);
    for (int k = 15; k >= 0; k--)
        if (depth[f[a][k]] >= depth[b])
            a = f[a][k];

    if (a == b)  return a;
    for (int k = 15; k >= 0; k--)
        if (f[a][k] != f[b][k])
        {
            a = f[a][k];
            b = f[b][k];
        }
    return f[a][0];
}

int main()
{
    scanf("%d", &n);
    int root = 0;
    memset(h, -1, sizeof h);
    for (int i = 0; i < n; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        if (b == -1) root = a;
        else add(a, b), add(b, a);
    }

    bfs(root);

    scanf("%d", &m);
    while (m--)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        int p = lca(a, b);
        if (p == a)  puts("1");
        else if (p == b) puts("2");
        else puts("0");
    }
    return 0;
}